import React, { useState } from 'react';
import { Modal, Checkbox, Table, Input, Button, Select, Tabs, Space } from 'antd';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import type { CheckboxOptionType, GetProp } from 'antd';
import { ArrowRightOutlined, ArrowLeftOutlined } from '@ant-design/icons';

interface FieldItem {
    value: string;
    label: string;
    inputType: 'input' | 'select' | 'treeSelect';
    options?: { label: string; value: string }[];
}

const FilterAndGroupConfigModal: React.FC = ({open,setOpen}) => {
    const [visible, setVisible] = useState(true);
    const [activeTab, setActiveTab] = useState('filter');

    // 过滤条件配置状态
    const [filterSelectedFields, setFilterSelectedFields] = useState<string[]>(['题名', '树形下拉框', '头像']);
    const [filterDefaultValues, setFilterDefaultValues] = useState<Record<string, string>>({});

    // 分组配置状态
    const [groupSelectedFields, setGroupSelectedFields] = useState<string[]>([]);
    const [groupDefaultValues, setGroupDefaultValues] = useState<Record<string, string>>({});

    const allFields: FieldItem[] = [
        { value: '档号', label: '档号', inputType: 'input' },
        { value: '年度', label: '年度', inputType: 'input' },
        { value: '机构', label: '机构', inputType: 'input' },
        { value: '文号', label: '文号', inputType: 'input' },
        { value: '成文日期', label: '成文日期', inputType: 'input' },
        { value: '盒号', label: '盒号', inputType: 'input' },
        { value: '件号', label: '件号', inputType: 'input' },
        { value: '创建时间', label: '创建时间', inputType: 'input' },
        { value: '密级', label: '密级', inputType: 'select', options: [
                { label: '公开', value: '公开' },
                { label: '内部', value: '内部' },
                { label: '秘密', value: '秘密' },
                { label: '机密', value: '机密' }
            ]},
        { value: '保管期限', label: '保管期限', inputType: 'input' },
        { value: '页数', label: '页数', inputType: 'input' },
        { value: '归档时间', label: '归档时间', inputType: 'input' },
        { value: '题名', label: '题名', inputType: 'input' },
        { value: '树形下拉框', label: '树形下拉框', inputType: 'treeSelect' },
        { value: '头像', label: '头像', inputType: 'input' },
    ];

    // 处理字段选择变化
    const handleFilterFieldChange = (checkedValues: CheckboxValueType[]) => {
        console.log('checkedValues=',checkedValues)
        setFilterSelectedFields(checkedValues as string[]);
    };

    const handleGroupFieldChange = (checkedValues: CheckboxValueType[]) => {
        console.log('handleGroupFieldChange=',checkedValues)
        setGroupSelectedFields(checkedValues as string[]);
    };

    // 处理默认值变化
    const handleFilterDefaultValueChange = (fieldName: string, value: string) => {
        setFilterDefaultValues(prev => ({
            ...prev,
            [fieldName]: value
        }));
    };

    const handleGroupDefaultValueChange = (fieldName: string, value: string) => {
        setGroupDefaultValues(prev => ({
            ...prev,
            [fieldName]: value
        }));
    };

    // 移动字段
    const moveField = (fieldName: string, from: string[], to: string[], setFrom: React.Dispatch<React.SetStateAction<string[]>>, setTo: React.Dispatch<React.SetStateAction<string[]>>) => {
        setFrom(prev => prev.filter(f => f !== fieldName));
        setTo(prev => [...prev, fieldName]);
    };

    const handleSave = () => {
        console.log('保存配置:', {
            filter: { selectedFields: filterSelectedFields, defaultValues: filterDefaultValues },
            group: { selectedFields: groupSelectedFields, defaultValues: groupDefaultValues }
        });
        setVisible(false);
    };

    // 渲染字段配置表格
    const renderFieldTable = (selectedFields: string[], handleDefaultValueChange: (fieldName: string, value: string) => void) => {
        const columns = [
            {
                title: '字段名称',
                dataIndex: 'name',
                key: 'name',
            },
            {
                title: '默认值',
                dataIndex: 'defaultValue',
                key: 'defaultValue',
                render: (_: any, record: FieldItem) => {
                    const field = allFields.find(f => f.name === record.name);
                    if (!field) return null;

                    if (field.inputType === 'select') {
                        return (
                            <Select
                                style={{ width: '100%' }}
                                placeholder="请选择"
                                onChange={(value) => handleDefaultValueChange(record.name, value)}
                                options={field.options}
                            />
                        );
                    }

                    if (field.inputType === 'treeSelect') {
                        return (
                            <Select
                                style={{ width: '100%' }}
                                placeholder="请选择"
                                onChange={(value) => handleDefaultValueChange(record.name, value)}
                                options={[
                                    { label: '树形选项1', value: 'tree1' },
                                    { label: '树形选项2', value: 'tree2' }
                                ]}
                            />
                        );
                    }

                    return (
                        <Input
                            placeholder={`请输入${record.name}`}
                            onChange={(e) => handleDefaultValueChange(record.name, e.target.value)}
                        />
                    );
                },
            },
        ];
        console.log({allFields, selectedFields})

        const dataSource = allFields.filter(field => selectedFields.includes(field.name));

        return (
            <Table
                columns={columns}
                dataSource={dataSource}
                rowKey="name"
                pagination={false}
                size="small"
            />
        );
    };

    const optionsWithDisabled: CheckboxOptionType<string>[] = [
        { label: 'Apple', value: 'Apple', className: 'label-1' },
        { label: 'Pear', value: 'Pear', className: 'label-2' },
        { label: 'Orange', value: 'Orange', className: 'label-3', disabled: false },
    ];

    // 渲染字段选择部分
    const renderFieldSelection = (
        unselectedFields: string[],
        selectedFields: string[],
        handleFieldChange: (checkedValues: CheckboxValueType[]) => void,
        moveField: (fieldName: string) => void
    ) => {
        return (
            <div style={{ display: 'flex', gap: '20px' }}>
                <div style={{ flex: 1 }}>
                    <h4>未选中数据</h4>
                    <Checkbox.Group
                        options={allFields}
                        defaultValue={['Apple']}
                        onChange={handleFieldChange}
                        style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', }}
                    />
                    {/*<Checkbox.Group*/}
                    {/*    value={selectedFields}*/}
                    {/*    onChange={handleFieldChange}*/}
                    {/*    style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', }}*/}
                    {/*>*/}
                    {/*    {allFields.filter(field => unselectedFields.includes(field.name)).map(field => (*/}
                    {/*        <div key={field.name} style={{ display: 'flex', alignItems: 'center', height:'40px' }}>*/}
                    {/*            <Checkbox value={field.name}>{field.label}</Checkbox>*/}
                    {/*            <Button*!/*/}
                    {/*                type="text"*!/*/}
                    {/*                icon={<ArrowRightOutlined />}*!/*/}
                    {/*                onClick={() => moveField(field.name)}*!/*/}
                    {/*            />*!/*/}
                    {/*        </div>*/}
                    {/*    ))}*/}
                    {/*</Checkbox.Group>*/}
                </div>

                <div style={{ flex: 1 }}>
                    <h4>已选中数据</h4>
                    {renderFieldTable(selectedFields, activeTab === 'filter' ? handleFilterDefaultValueChange : handleGroupDefaultValueChange)}
                </div>
            </div>
        );
    };

    return (
        <Modal
            title="配置"
            open={open}
            width={1000}
            onCancel={() => setOpen(false)}
            footer={[
                <Button key="cancel" onClick={() => setVisible(false)}>
                    取消
                </Button>,
                <Button key="save" type="primary" onClick={handleSave}>
                    保存
                </Button>,
            ]}
        >
            <Tabs activeKey={activeTab} onChange={setActiveTab} style={{height:'500px'}}>
                <Tabs.TabPane tab="过滤条件配置" key="filter">
                    {renderFieldSelection(
                        allFields.map(f => f.name).filter(name => !filterSelectedFields.includes(name)),
                        filterSelectedFields,
                        handleFilterFieldChange,
                        (fieldName) => moveField(
                            fieldName,
                            allFields.map(f => f.name).filter(name => !filterSelectedFields.includes(name)),
                            filterSelectedFields,
                            () => {},
                            setFilterSelectedFields
                        )
                    )}
                </Tabs.TabPane>
                <Tabs.TabPane tab="分组配置" key="group">
                    {renderFieldSelection(
                        allFields.map(f => f.name).filter(name => !groupSelectedFields.includes(name)),
                        groupSelectedFields,
                        handleGroupFieldChange,
                        (fieldName) => moveField(
                            fieldName,
                            allFields.map(f => f.name).filter(name => !groupSelectedFields.includes(name)),
                            groupSelectedFields,
                            () => {},
                            setGroupSelectedFields
                        )
                    )}
                </Tabs.TabPane>
            </Tabs>
        </Modal>
    );
};

export default FilterAndGroupConfigModal;